package com.example.backend.controller;

import com.example.backend.domain.entity.*;
import com.example.backend.domain.enums.CommentType;
import com.example.backend.dto.ApiResponse;
import com.example.backend.service.TicketCollaborationService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.util.List;
import java.util.Map;

/**
 * 工单协作控制器
 * 提供@用户、内部讨论、关注、转发、批量操作等功能
 */
@Tag(name = "工单协作管理", description = "工单协作功能接口")
@RestController
@RequestMapping("/api/ticket-collaboration")
public class TicketCollaborationController {

    @Autowired
    private TicketCollaborationService collaborationService;

    // ==================== @用户功能 ====================

    @Operation(summary = "创建带@用户的评论", description = "创建评论并@指定用户")
    @PostMapping("/comments/with-mentions")
    public ResponseEntity<ApiResponse<Comment>> createCommentWithMentions(
            @Parameter(description = "工单ID") @RequestParam Long ticketId,
            @Parameter(description = "作者ID") @RequestParam Long authorId,
            @Parameter(description = "评论内容") @RequestParam String content,
            @Parameter(description = "评论类型") @RequestParam(defaultValue = "PUBLIC") CommentType commentType,
            @Parameter(description = "是否内部评论") @RequestParam(defaultValue = "false") Boolean isInternal,
            @Parameter(description = "父评论ID") @RequestParam(required = false) Long parentId) {
        
        try {
            Comment comment = collaborationService.createCommentWithMentions(
                null, null, content, commentType, isInternal, null);
            return ResponseEntity.ok(ApiResponse.success("创建评论成功", comment));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("创建评论失败: " + e.getMessage()));
        }
    }

    @Operation(summary = "获取评论中@的用户", description = "获取评论中@的用户列表")
    @GetMapping("/comments/{commentId}/mentioned-users")
    public ResponseEntity<ApiResponse<List<User>>> getMentionedUsers(
            @Parameter(description = "评论ID") @PathVariable Long commentId) {
        
        try {
            // 这里需要根据commentId获取Comment对象
            // 暂时返回空列表
            return ResponseEntity.ok(ApiResponse.success("获取@用户成功", List.of()));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取@用户失败: " + e.getMessage()));
        }
    }

    // ==================== 内部讨论功能 ====================

    @Operation(summary = "创建内部讨论", description = "创建工单内部讨论评论")
    @PostMapping("/discussions")
    public ResponseEntity<ApiResponse<Comment>> createDiscussion(
            @Parameter(description = "工单ID") @RequestParam Long ticketId,
            @Parameter(description = "作者ID") @RequestParam Long authorId,
            @Parameter(description = "讨论内容") @RequestParam String content,
            @Parameter(description = "讨论类型") @RequestParam(defaultValue = "GENERAL") String discussionType,
            @Parameter(description = "是否紧急") @RequestParam(defaultValue = "false") Boolean isUrgent) {
        
        try {
            Comment comment = collaborationService.createDiscussionComment(
                null, null, content, discussionType, isUrgent);
            return ResponseEntity.ok(ApiResponse.success("创建内部讨论成功", comment));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("创建内部讨论失败: " + e.getMessage()));
        }
    }

    @Operation(summary = "获取工单内部讨论", description = "获取工单的内部讨论列表")
    @GetMapping("/discussions/{ticketId}")
    public ResponseEntity<ApiResponse<List<Comment>>> getTicketDiscussions(
            @Parameter(description = "工单ID") @PathVariable Long ticketId) {
        
        try {
            List<Comment> discussions = collaborationService.getTicketDiscussions(ticketId);
            return ResponseEntity.ok(ApiResponse.success("获取内部讨论成功", discussions));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取内部讨论失败: " + e.getMessage()));
        }
    }

    // ==================== 关注/收藏功能 ====================

    @Operation(summary = "关注工单", description = "关注指定工单")
    @PostMapping("/follow")
    public ResponseEntity<ApiResponse<TicketFollow>> followTicket(
            @Parameter(description = "工单ID") @RequestParam Long ticketId,
            @Parameter(description = "用户ID") @RequestParam Long userId,
            @Parameter(description = "关注类型") @RequestParam(defaultValue = "FOLLOW") String followType,
            @Parameter(description = "是否启用通知") @RequestParam(defaultValue = "true") Boolean notificationEnabled,
            @Parameter(description = "通知类型") @RequestParam(required = false) List<String> notificationTypes) {
        
        try {
            TicketFollow follow = collaborationService.followTicket(
                ticketId, userId, followType, notificationEnabled, notificationTypes);
            return ResponseEntity.ok(ApiResponse.success("关注工单成功", follow));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("关注工单失败: " + e.getMessage()));
        }
    }

    @Operation(summary = "取消关注工单", description = "取消关注指定工单")
    @DeleteMapping("/follow")
    public ResponseEntity<ApiResponse<Void>> unfollowTicket(
            @Parameter(description = "工单ID") @RequestParam Long ticketId,
            @Parameter(description = "用户ID") @RequestParam Long userId) {
        
        try {
            collaborationService.unfollowTicket(ticketId, userId);
            return ResponseEntity.ok(ApiResponse.success("取消关注成功", null));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("取消关注失败: " + e.getMessage()));
        }
    }

    @Operation(summary = "检查是否关注工单", description = "检查用户是否关注了指定工单")
    @GetMapping("/follow/check")
    public ResponseEntity<ApiResponse<Boolean>> isFollowingTicket(
            @Parameter(description = "工单ID") @RequestParam Long ticketId,
            @Parameter(description = "用户ID") @RequestParam Long userId) {
        
        try {
            boolean isFollowing = collaborationService.isFollowingTicket(ticketId, userId);
            return ResponseEntity.ok(ApiResponse.success("检查关注状态成功", isFollowing));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("检查关注状态失败: " + e.getMessage()));
        }
    }

    @Operation(summary = "获取用户关注的工单", description = "获取用户关注的所有工单")
    @GetMapping("/follow/user/{userId}")
    public ResponseEntity<ApiResponse<List<TicketFollow>>> getUserFollowedTickets(
            @Parameter(description = "用户ID") @PathVariable Long userId) {
        
        try {
            List<TicketFollow> follows = collaborationService.getUserFollowedTickets(userId);
            return ResponseEntity.ok(ApiResponse.success("获取关注工单成功", follows));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取关注工单失败: " + e.getMessage()));
        }
    }

    @Operation(summary = "获取工单关注用户", description = "获取关注指定工单的所有用户")
    @GetMapping("/follow/ticket/{ticketId}")
    public ResponseEntity<ApiResponse<List<TicketFollow>>> getTicketFollowers(
            @Parameter(description = "工单ID") @PathVariable Long ticketId) {
        
        try {
            List<TicketFollow> followers = collaborationService.getTicketFollowers(ticketId);
            return ResponseEntity.ok(ApiResponse.success("获取关注用户成功", followers));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取关注用户失败: " + e.getMessage()));
        }
    }

    // ==================== 工单转发功能 ====================

    @Operation(summary = "转发工单", description = "将工单转发给其他用户")
    @PostMapping("/forward")
    public ResponseEntity<ApiResponse<TicketForward>> forwardTicket(
            @Parameter(description = "工单ID") @RequestParam Long ticketId,
            @Parameter(description = "发送者ID") @RequestParam Long fromUserId,
            @Parameter(description = "接收者ID") @RequestParam Long toUserId,
            @Parameter(description = "转发类型") @RequestParam String forwardType,
            @Parameter(description = "转发原因") @RequestParam(required = false) String reason,
            @Parameter(description = "优先级") @RequestParam(required = false) String priority,
            @Parameter(description = "截止时间") @RequestParam(required = false) String dueDate) {
        
        try {
            Instant dueDateInstant = dueDate != null ? Instant.parse(dueDate) : null;
            TicketForward forward = collaborationService.forwardTicket(
                ticketId, fromUserId, toUserId, forwardType, reason, priority, dueDateInstant);
            return ResponseEntity.ok(ApiResponse.success("转发工单成功", forward));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("转发工单失败: " + e.getMessage()));
        }
    }

    @Operation(summary = "响应转发", description = "响应工单转发请求")
    @PostMapping("/forward/{forwardId}/respond")
    public ResponseEntity<ApiResponse<TicketForward>> respondToForward(
            @Parameter(description = "转发ID") @PathVariable Long forwardId,
            @Parameter(description = "响应状态") @RequestParam String status,
            @Parameter(description = "响应消息") @RequestParam(required = false) String responseMessage) {
        
        try {
            TicketForward forward = collaborationService.respondToForward(forwardId, status, responseMessage);
            return ResponseEntity.ok(ApiResponse.success("响应转发成功", forward));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("响应转发失败: " + e.getMessage()));
        }
    }

    @Operation(summary = "获取用户转发记录", description = "获取用户的工单转发记录")
    @GetMapping("/forward/user/{userId}")
    public ResponseEntity<ApiResponse<List<TicketForward>>> getUserForwards(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @Parameter(description = "状态过滤") @RequestParam(required = false) String status) {
        
        try {
            List<TicketForward> forwards = collaborationService.getUserForwards(userId, status);
            return ResponseEntity.ok(ApiResponse.success("获取转发记录成功", forwards));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取转发记录失败: " + e.getMessage()));
        }
    }

    // ==================== 批量操作功能 ====================

    @Operation(summary = "创建批量操作", description = "创建批量操作任务")
    @PostMapping("/batch-operations")
    public ResponseEntity<ApiResponse<BatchOperation>> createBatchOperation(
            @Parameter(description = "操作类型") @RequestParam String operationType,
            @Parameter(description = "操作名称") @RequestParam String operationName,
            @Parameter(description = "工单ID列表") @RequestParam List<Long> ticketIds,
            @Parameter(description = "操作者ID") @RequestParam Long operatorId,
            @Parameter(description = "操作参数") @RequestParam Map<String, Object> operationData) {
        
        try {
            BatchOperation operation = collaborationService.createBatchOperation(
                operationType, operationName, ticketIds, operatorId, operationData);
            return ResponseEntity.ok(ApiResponse.success("创建批量操作成功", operation));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("创建批量操作失败: " + e.getMessage()));
        }
    }

    @Operation(summary = "执行批量操作", description = "执行指定的批量操作")
    @PostMapping("/batch-operations/{operationId}/execute")
    public ResponseEntity<ApiResponse<BatchOperation>> executeBatchOperation(
            @Parameter(description = "操作ID") @PathVariable Long operationId) {
        
        try {
            BatchOperation operation = collaborationService.executeBatchOperation(operationId);
            return ResponseEntity.ok(ApiResponse.success("执行批量操作成功", operation));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("执行批量操作失败: " + e.getMessage()));
        }
    }

    @Operation(summary = "获取用户批量操作记录", description = "获取用户的批量操作记录")
    @GetMapping("/batch-operations/user/{userId}")
    public ResponseEntity<ApiResponse<List<BatchOperation>>> getUserBatchOperations(
            @Parameter(description = "用户ID") @PathVariable Long userId) {
        
        try {
            List<BatchOperation> operations = collaborationService.getUserBatchOperations(userId);
            return ResponseEntity.ok(ApiResponse.success("获取批量操作记录成功", operations));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取批量操作记录失败: " + e.getMessage()));
        }
    }

    @Operation(summary = "获取批量操作统计", description = "获取用户的批量操作统计信息")
    @GetMapping("/batch-operations/stats/{userId}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getBatchOperationStats(
            @Parameter(description = "用户ID") @PathVariable Long userId) {
        
        try {
            Map<String, Object> stats = collaborationService.getBatchOperationStats(userId);
            return ResponseEntity.ok(ApiResponse.success("获取批量操作统计成功", stats));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取批量操作统计失败: " + e.getMessage()));
        }
    }

    // ==================== 协作概览 ====================

    @Operation(summary = "获取协作概览", description = "获取工单协作功能的概览信息")
    @GetMapping("/overview/{ticketId}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getCollaborationOverview(
            @Parameter(description = "工单ID") @PathVariable Long ticketId) {
        
        try {
            // 获取工单的协作信息
            List<TicketFollow> followers = collaborationService.getTicketFollowers(ticketId);
            List<Comment> discussions = collaborationService.getTicketDiscussions(ticketId);
            
            Map<String, Object> overview = Map.of(
                "followersCount", followers.size(),
                "discussionsCount", discussions.size(),
                "followers", followers.stream().limit(5).toList(),
                "recentDiscussions", discussions.stream().limit(3).toList()
            );
            
            return ResponseEntity.ok(ApiResponse.success("获取协作概览成功", overview));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取协作概览失败: " + e.getMessage()));
        }
    }
}
